package com.xysq.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.CouponModel;
import com.rockcent.model.constant.ModelType;
import com.umeng.analytics.MobclickAgent;
import com.xysq.activity.CommodityDetailsActivity;
import com.xysq.activity.QRCodeActivity;
import com.xysq.adapter.BaseDataAdapter;
import com.xysq.XYApplication;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.CustomBaseDialog;
import com.xysq.widget.LoadData;
import com.xysq.widget.ScrollListener;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by huangdongkai on 2015/7/22.
 */
public class UnUseTicketsFragment extends BaseFragment implements View.OnClickListener {
    private String loginName;
    private String keyWords = "";
    private int state = 0;
    public static final int type = 0;
    private MyTicketsAdapter myTicketsAdapter;
    int id;
    int count;
    String name;
    int isDelivery;
    int couponNumber;
    ModelType modelType;

    @InjectView(R.id.swipe)
    SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.list_data)
    ListView dataList;
    @InjectView(R.id.progress_loading)
    ProgressBar progressBar;
    @InjectView(R.id.txt_empty)
    TextView emptyTxt;
    @InjectView(R.id.layout_set_number)
    LinearLayout setNumberLayout;
    @InjectView(R.id.img_plus)
    ImageView plusImg;
    @InjectView(R.id.img_minus)
    ImageView minusImg;
    @InjectView(R.id.edit_number_count)
    EditText numberCountEdit;
    @InjectView(R.id.btn_cancle)
    Button cancleBtn;
    @InjectView(R.id.btn_confirm)
    Button confirmBtn;
    ScrollListener scrollListener;

    public static UnUseTicketsFragment newInstance(int position) {
        UnUseTicketsFragment fragment = new UnUseTicketsFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflaterView(inflater, R.layout.activity_unuse_tickets, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        cancleBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        plusImg.setOnClickListener(this);
        minusImg.setOnClickListener(this);
        loginName = UserInfoKeeper.readPhoneNumber(getActivity());
        myTicketsAdapter = new MyTicketsAdapter(getActivity());
        dataList.setAdapter(myTicketsAdapter);
        scrollListener = new ScrollListener(dataList, true, new LoadData() {
            @Override
            public void loadMyData() {
                getData();
            }
        });
        dataList.setOnScrollListener(scrollListener);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                scrollListener.setCurrentPage(1);
                myTicketsAdapter.clearItems();
                getData();
            }
        });
    }

    private void getData() {
        progressBar.setVisibility(View.VISIBLE);
        appAction.listCouponWallet(loginName, keyWords, state, type, scrollListener.getCurrentPage(), 20, new CallbackListener<List<CouponModel>>() {
            @Override
            public void onSuccess(List<CouponModel> data) {
                swipeRefreshLayout.setRefreshing(false);
                progressBar.setVisibility(View.GONE);
                if (scrollListener.getCurrentPage() == 1) {
                    if (data.isEmpty()) {
                        emptyTxt.setVisibility(View.VISIBLE);
                    } else {
                        emptyTxt.setVisibility(View.GONE);
                        myTicketsAdapter.setItems(data);
                    }
                } else {
                    if(data.isEmpty()){
                        scrollListener.setLoadFinish(false);
                    }else {
                        scrollListener.setLoadFinish(true);
                        emptyTxt.setVisibility(View.GONE);
                        myTicketsAdapter.addItems(data);
                    }
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                swipeRefreshLayout.setRefreshing(false);
                progressBar.setVisibility(View.GONE);
                scrollListener.setLoadFinish(true);
            }
        });
    }

    @Override
    public void onClick(View view) {
        if (!numberCountEdit.getText().toString().equals(null) & !numberCountEdit.getText().toString().equals("")) {
            count = Integer.parseInt(numberCountEdit.getText().toString());
        } else {
            count = 1;
        }
        if (view == plusImg) {
            if (count < couponNumber) {
                numberCountEdit.setText(String.valueOf(count + 1));
            }
        }
        if (view == minusImg) {
            if (count > 1) {
                numberCountEdit.setText(String.valueOf(count - 1));
            }
        }
        if (view == cancleBtn) {
            MobclickAgent.onEvent(getActivity(), "1021");
            numberCountEdit.setText(String.valueOf(1));
            setNumberLayout.setVisibility(View.GONE);
        }
        if (view == confirmBtn) {
            MobclickAgent.onEvent(getActivity(), "1020");
            if (!numberCountEdit.getText().toString().equals("")) {
                if (count <= couponNumber & count > 0) {
                    setNumberLayout.setVisibility(View.GONE);
                    numberCountEdit.setText(String.valueOf(1));
                    Intent intent = new Intent(getActivity(), QRCodeActivity.class);
                    intent.putExtra("count", count);
                    intent.putExtra("id", id);
                    intent.putExtra("name", name);
                    intent.putExtra("isDelivery", isDelivery);
                    intent.putExtra("modelType", modelType);

                    startActivity(intent);
                } else {
                    Log.e("number", "count:" + count + " couponNumber: " + couponNumber);
                    ToastUtil.showLong(getActivity(), R.string.toast_un_enough_coupon);
                }
            } else {
                ToastUtil.showShort(getActivity(), R.string.toast_correct_number);
            }
        }
    }

    public class MyTicketsAdapter extends BaseDataAdapter<CouponModel> {
        private boolean mIsNeedReload = false;
        private Context mContext;

        public MyTicketsAdapter(Context context) {
            super(context);
            mContext = context;
        }

        public boolean isNeedReload() {
            return mIsNeedReload;
        }

        public void setNeedReload(boolean isNeedReload) {
            mIsNeedReload = isNeedReload;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_my_tickets, viewGroup, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final CouponModel coupon = itemList.get(position);
            String logoUrl = coupon.getPicUrl().split(";")[0];
            if (!TextUtils.isEmpty(logoUrl)) {
                logoUrl = PropertiesUtil.getImageServer() + logoUrl;
                XYApplication.getImageLoader().displayImage(logoUrl, holder.picIv);
            }
//            couponNumber = coupon.getCount();
            holder.nameOtherTxt.setText(coupon.getIntroduce());
            holder.nameTxt.setText(coupon.getName());
            String time = UseUtil.timeToDate(coupon.getUseEndTime());
            holder.timeTxt.setText(time);
            holder.numTxt.setText(String.valueOf(coupon.getCount()));
            holder.exchangeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (coupon.getUseStartTime() > System.currentTimeMillis()) {
                        ToastUtil.showShort(mContext, "该券" + UseUtil.timeToDate(coupon.getUseStartTime()) + "可使用");
                    } else {
                        MobclickAgent.onEvent(getActivity(), "1019");
//                        setNumberLayout.setVisibility(View.VISIBLE);
                        couponNumber = coupon.getCount();
                        id = coupon.getId();
                        count = 1;
                        name = coupon.getName();
                        isDelivery = Integer.valueOf(coupon.getIsDelivery());
                        modelType = coupon.getModelType();
                        CustomBaseDialog customBaseDialog = new CustomBaseDialog(getActivity(), couponNumber, id, name, isDelivery, modelType);
                        customBaseDialog.show();
                    }
                }
            });
            holder.jumpClickAreaLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
                    intent.putExtra(CommodityDetailsActivity.COUPONMODEL_ID, coupon.getId());
                    startActivity(intent);
                }
            });
            return convertView;
        }

        class ViewHolder {

            @InjectView(R.id.layout_jump_click_area)
            LinearLayout jumpClickAreaLayout;
            @InjectView(R.id.iv_pic)
            ImageView picIv;
            @InjectView(R.id.txt_customer_name)
            TextView nameTxt;
            @InjectView(R.id.txt_other_name)
            TextView nameOtherTxt;
            @InjectView(R.id.txt_num)
            TextView numTxt;
            @InjectView(R.id.txt_time)
            TextView timeTxt;
            @InjectView(R.id.btn_exchange)
            Button exchangeBtn;

            public ViewHolder(View view) {
                ButterKnife.inject(this, view);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的全包未使用");
        scrollListener.setCurrentPage(1);
        myTicketsAdapter.clearItems();
        getData();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的券包未使用");
    }
}
